package com.yimo.imgtransfer;

import com.google.gson.Gson;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import com.qiniu.util.StringMap;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

@Service
public class QiniuService {
    @Value("${qiniu.accessKey}")
    public String accessKey;

    @Value("${qiniu.secretKey}")
    public String secretKey;

    @Value("${qiniu.bucket}")
    public String bucket;

    @Value("${qiniu.url}")
    public String url;
    Configuration cfg = new Configuration(Zone.zone0());
    UploadManager uploadManager = new UploadManager(cfg);

    public String getUploadToken() {
        Auth auth = Auth.create(accessKey, secretKey);
        StringMap putPolicy = new StringMap();
        putPolicy.put("returnBody", "{\"key\":\"$(key)\",\"w\":\"$(imageInfo.width)\",\"h\":\"$(imageInfo.height)\"}");
        long expireSeconds = 600;
        String upToken = auth.uploadToken(bucket, null, expireSeconds, putPolicy);
        System.out.println(upToken);
        return upToken;
    }

    public String uploadImage(BufferedImage image) throws IOException {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ImageIO.write(image, "png", baos);
        Response response = uploadManager.put(baos.toByteArray(), null, getUploadToken());
        //解析上传成功的结果
        DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
        return url + putRet.key;
    }

    public String uploadImageFromBytes(byte[] dataBytes) throws IOException {
        Response response = uploadManager.put(dataBytes, null, getUploadToken());
        //解析上传成功的结果
        DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
        return url + putRet.key;
    }
}